<template>
	<view>
		<u-navbar title="分類管理" placeholder autoBack>
			<view class="flexright xiaohui" slot="right" @click="addflshow=true">添加</view>
		</u-navbar>
		<u-sticky>
			<view class="ffffff mainpadding_top">
				<scroll-view scroll-x="true" style="width: calc(100vw - 30rpx);">
					<view class="flexleft">
						<view class="flexleft hei_text main_size bold" v-for="(item,index) in topList" :key="index">
							<text class="margin_right1" style="white-space: nowrap;"
								@click="back(item,index)">{{item.name}}</text>
							<view class="arrowright1" v-show="index!=topList.length-1"></view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-sticky>
		<view class="mainpadding" style="padding-bottom: 150rpx;">
			<view class="flexbetween bghuang mainpadding radius">
				<view class="hei_text bold main_size">第{{topList.length}}層分類</view>
				<view class="flexright" @click="jumpdetail('/pages/workbench/classpx?id=',pid)" v-if="list.data.length">
					<u-icon name="list" color="#333" size="18"></u-icon>
					<view class="hei_text bold main_size">排序</view>
				</view>
			</view>
			<view class="margin_top flexleft" style="margin-left: 60rpx;">
				<view class="itemlefttab borderhui huang_text main_size bold">代號</view>
				<view class="itemcentertab borderhui huang_text main_size bold">分類</view>
				<view class="itemrighttab borderhui huang_text main_size bold">產品</view>
			</view>
			<view class="margin_top flexleft" style="position: relative;" v-for="item in list.data" :key="item.id">
				<u-switch activeValue="1" inactiveValue="2" asyncChange inactiveColor="rgb(230, 230, 230)" size="16"
					v-model="item.status" activeColor="#ffb800" @change="changejd(item.status,item.id)"></u-switch>
				<view class="itemlefttab borderhui hei_text main_size bold" @click="classLableClick(item)">
					{{item.codename}}
				</view>
				<view class="itemcentertab borderhui hei_text main_size bold" @click="classLableClick(item)">
					{{item.name}}
				</view>
				<view class="itemrighttab borderhui hei_text main_size bold" @click="classLableClick(item)">
					{{item.productname}}
				</view>
				<view class="tiebianarrow flexcenter" v-if="item.is_haschild" @click="classLableClick(item)">
					<view class="arrowright2"></view>
				</view>
			</view>
		</view>
		<view class="ffffff posibottom flexbetween mainpadding" style="bottom: 0;">
			<view class="baibtn bghuang radius hei_text smalltext bold" @click="goCommGoods" v-if="list.data.length!=0">
				組合商品</view>
			<view class="baibtn radius smalltext bold" style="background-color: #029a47;color: #fff;" @click="exclehr">
				Excel匯入</view>
			<view class="baibtn bghuang radius hei_text smalltext bold" @click="copyCate">整頁複製</view>
			<view class="baibtn radius smalltext bold" style="background-color: #029a47;color: #fff;" @click="excelfl">
				Excel範例</view>
			<view class="baibtn bghuang radius hei_text smalltext bold" @click="copyPaste">整頁貼上</view>
			<view class="baibtn bghuang radius hei_text smalltext bold" v-if="type==1" @click="backPage">確定</view>
		</view>
		<u-modal :show="addflshow" :title="title" closeOnClickOverlay @close="addflshow=false" confirmColor="#ffb800"
			confirmText="確認" cancelText="取消" @confirm="addflSure">
			<view class="slot-content">
				<view class="margin_top">
					<u--input placeholder="代號編碼" border="surround" inputAlign="center" v-model="codename"></u--input>
				</view>
				<view class="margin_top">
					<u--input placeholder="分類名稱" :trim="false" border="surround" inputAlign="center" tran
						v-model="name"></u--input>
				</view>
				<view class="flexcenter margin_top" @click="productname=name">
					<u-icon name="arrow-downward" color="#e83428" size="28"></u-icon>
					<view class="xiaobai  bold margin_left1 main_size radius"
						style="padding: 5rpx 40rpx;background-color: #e83428;">複製</view>
				</view>
				<view class="margin_top">
					<u--input placeholder="產品名稱" :trim="false" border="surround" inputAlign="center"
						v-model="productname"></u--input>
				</view>
			</view>
		</u-modal>
		<u-popup :show="editshow" mode="center" @close="editshow = false" round="10">
			<view class="mainpadding_top">
				<view class="flexcenter titletext bold hei_text">選擇操作類型</view>
				<view class="surebtn2 flexcenter mainpadding margin_top main_size bold" @click="editCate">編輯</view>
				<view class="resetbtn2 flexcenter ffffff mainpadding margin_top2 huang_text main_size bold"
					@click="removeCate">刪除</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import m_excel from '../../uni_modules/m-excel/m-excel/js_sdk';
	const httpRequest = require("@/common/httpRequest.js")
	// 确保正确导入xlsx库
	import * as XLSX from 'xlsx' // 推荐这种完整导入方式
	export default {
		data() {
			return {
				type: "", //1選擇分类
				title: "添加分類",
				addflshow: false, //添加分类
				editshow: false, //编辑分类
				lastTapDiffTime: 0,
				lastTapTimeoutFunc: null,
				codename: "", //代号名称
				name: "", //分类名称
				productname: "", //产品名称
				shop_id: uni.getStorageSync("shop_id"), //当前店鋪id
				pid: 0, //当前分类id
				pid_status: 1, //当前分类状态
				list: {
					data: []
				}, //分类列表
				editCateInfo: "", //要编辑的分类信息
				topList: [{
					name: "首頁",
					id: 0
				}], //顶部展示列表
				copyIdList: [], //整页复制id
				excelData: []
			}
		},
		onLoad(options) {
			if (options.type) {
				this.type = options.type
			}
			// 验证XLSX库是否成功导入
			if (typeof XLSX === 'undefined') {
				console.error('XLSX is undefined')
			} else {
				console.log('XLSX库加载成功', XLSX)
			}
		},
		watch: {
			addflshow(newVal) {
				if (!newVal) {
					this.title = "添加分類"
					this.codename = ""
					this.name = ""
					this.productname = ""
					this.editCateInfo = ""
				}
			},
		},
		onShow() {
			this.getCateList()
		},
		methods: {
			changejd(datas, id) {
				let _this = this;
				if (_this.pid_status == 2 && datas == 2) return false;
				let datalist = _this.list.data;
				let editData = {
					shop_id: _this.shop_id, //店鋪id
					id: id, //分类id
					status: datas == 2 ? 1 : 2
				};
				uni.showLoading({
					mask: true,
					title: "請稍後"
				})
				_this.http.request("/api/shop/editClass", 'POST', editData).then(res => {
					uni.hideLoading()
					if (res.code == 1) {
						datalist = datalist.map(item =>
							item.id === id ? {
								...item,
								status: editData.status + ''
							} :
							item
						);
						_this.list.data = datalist;
					}
				})
			},
			async getCateList() { //分类列表
				let _this = this
				uni.showLoading({
					mask: true,
					title: "請稍後"
				})
				let res = await this.http.request('/api/shop/listClass', 'POST', {
					shop_id: this.shop_id, //店鋪id
					id: this.pid
				})
				uni.hideLoading()
				if (res.code == 1) {

					this.list.data = res.data
				} else {
					this.http.toast(res.msg)
				}
				this.addflshow = false
			},
			classLableClick(item) { // 單击或双击
				const _this = this;
				// 当前時間
				const curTime = new Date().getTime();
				// 上次点击時間
				const lastTime = _this.lastTapDiffTime;
				// 更新上次点击時間
				_this.lastTapDiffTime = curTime;
				// 两次点击间隔小于250毫秒, 认为是双击
				const diff = curTime - lastTime;
				if (diff < 250) {
					console.log('双击');
					this.editCateInfo = item
					this.editshow = true
					// 执行方法
					// _this.xxxxx()
					// 成功触发双击事件时，取消單击事件的执行
					clearTimeout(_this.lastTapTimeoutFunc);
				} else {
					// 單击事件延时250毫秒执行
					_this.lastTapTimeoutFunc = setTimeout(function() {
						// console.log('單击');
						if ((item.pid == 0 && item.is_haschild == 0) || (item.pid != 0 && item.is_haschild ==
								0)) {
							_this.pid = item.id;
							_this.pid_status = item.status;
							_this.list.data = []
						} else {
							_this.pid = item.id;
							_this.pid_status = item.status;
							_this.getCateList()
						}
						_this.topList.push(item)
						// console.log(_this.topList)
						// console.log(_this.pid)
						// 执行方法
						// _this.xxxxx()
					}, 250);
				}
			},
			editCate() { //編輯分類
				this.editshow = false
				this.title = "編輯分類"
				this.codename = this.editCateInfo.codename
				this.name = this.editCateInfo.name
				this.productname = this.editCateInfo.productname
				this.addflshow = true
			},
			async removeCate() { //刪除分类
				let res = await this.http.request('/api/shop/Classdel', 'POST', {
					shop_id: this.shop_id,
					id: this.editCateInfo.id
				})
				if (res.code == 1) {
					this.http.toast("刪除成功")
					let index = this.list.data.findIndex(item => {
						return this.editCateInfo.id == item.id
					})
					this.list.data.splice(index, 1)
					this.getCateList()
				} else if (res.code == 0) {
					this.http.toast(res.msg)
				} else {
					this.http.toast('系統處理中，請稍後再試');
				}
				this.editshow = false
			},
			copy() { //复制
				if (!this.name) {
					this.http.toast("請先輸入分類名稱再複製！")
					return false
				}
				this.productname = this.name
			},
			async addflSure() { // 添加分类
				let _this = this
				let url = "",
					text = "",
					data = {};
				// if (!this.codename) {
				// 	this.http.toast("請輸入代號名稱！")
				// 	return false
				// }
				if (!this.name) {
					this.http.toast("請輸入分類名稱！")
					return false
				}
				// if (!this.productname) {
				// 	this.http.toast("請输入產品名稱！")
				// 	return false
				// }
				if (!this.editCateInfo) { //添加分类
					url = "/api/shop/addClass"
					text = "添加成功"
					data = {
						shop_id: this.shop_id, //店鋪id
						pid: this.pid, //上级id
						codename: _this.codename, //代号名称
						name: _this.name, //分类名称
						productname: _this.productname, //产品名称
					}
				} else { //编辑分类
					url = "/api/shop/editClass"
					text = "修改成功"
					data = {
						shop_id: this.shop_id, //店鋪id
						id: this.editCateInfo.id, //分类id
						codename: _this.codename, //代号名称
						name: _this.name, //分类名称
						productname: _this.productname, //产品名称
					}
				}
				let res = await this.http.request(url, 'POST', data)
				if (res.code == 1) {
					this.http.toast(text)
					this.addflshow = false
					this.title = "添加分類"
					this.codename = ""
					this.name = ""
					this.productname = ""
					this.editCateInfo = ""
					this.getCateList()
				} else {
					this.http.toast(res.msg)
				}
			},
			back(item, index) { //点击顶部每一项返回上一分类
				this.pid = item.id;
				this.pid_status = item.id == 0 ? 1 : item.status;
				if (this.pid == 0) {
					this.topList = [{
						name: "首頁",
						id: 0
					}]
					this.getCateList()
				} else {
					this.topList.splice(index + 1)
					this.getCateList()
				}
			},
			async goCommGoods() { //组合商品
				uni.showLoading({
					title: "請稍後",
					mask: true
				})
				console.log(this.topList)
				let arr = []
				this.topList.forEach(item => {
					arr.push(item.id)
				})

				arr = arr.slice(1)
				console.log(arr)
				// return
				let res = await this.http.request('/api/goods/classGoods', 'POST', {
					shop_id: this.shop_id,
					ids: arr.join(), //分类连接
					current_id: this.topList[this.topList.length - 1].id, //当前分类ID
				})
				uni.hideLoading()
				if (res.code == 1) {
					this.http.toast("組合成功")
					// this.getCateList()
					setTimeout(() => {
						uni.redirectTo({
							url: "./shangpingl"
						})
					}, 500)
				} else if (res.code == 0) {
					this.http.toast(res.msg)
				} else {
					this.http.toast('系統處理中，請稍後再試');
				}
			},
			// 读取Excel文件
			readExcelFile(file) {
				console.log(file);
				this.excelData = []
				const reader = new FileReader()
				reader.onload = (e) => {
					try {
						// 解析Excel文件
						const data = new Uint8Array(e.target.result)
						const workbook = XLSX.read(data, {
							type: 'array'
						})

						// 获取第一个工作表名称
						const firstSheetName = workbook.SheetNames[0]
						const worksheet = workbook.Sheets[firstSheetName]

						// 将工作表转换为JSON
						const jsonData = XLSX.utils.sheet_to_json(worksheet, {
							header: 1
						})

						this.excelData = jsonData
						console.log(jsonData);
					} catch (error) {
						httpRequest.toast('解析Excel文件失败，请检查文件格式是否正确')
						console.error('Excel解析错误:', error)
					}
				}

				reader.onerror = () => {
					httpRequest.toast('文件读取失败，请重试')
				}

				// 以二进制方式读取文件
				reader.readAsArrayBuffer(file)
			},
			// 将Blob URL转换为Blob对象
			async blobUrlToBlob(blobUrl) {
				try {
					const response = await fetch(blobUrl)
					if (!response.ok) {
						throw new Error('无法获取Blob内容')
					}
					const blob = await response.blob()
					console.log('转换后的Blob对象:', blob) // 这才是真正的Blob对象
					this.readExcelFile(blob)
				} catch (err) {
					throw new Error('转换Blob URL失败: ' + err.message)
				}
			},
			exclehr() { //導入
				let _this = this
				uni.chooseFile({
					count: 1,
					type: 'file',
					success(res) {
						for (let i = 0; i < res.tempFiles.length; i++) {
							_this.blobUrlToBlob(res.tempFiles[i].path)
							return
							_this.uploadImageService(res.tempFiles[i].path)
						}
					}
				})
			},
			uploadImageService(url) {
				let _this = this;
				uni.showLoading({
					mask: true,
					title: "請稍後"
				})
				httpRequest.uploadFileshop('/api/common/upload', url).then(res => {
					uni.hideLoading()
					_this.upclass(res.url)
				}).catch(err => {
					uni.hideLoading()
				});
			},
			upclass(url) {
				uni.showLoading({
					mask: true,
					title: "請稍後"
				})
				httpRequest.request('/api/goods/index', 'GET', {
					file: url,
					shop_id: this.shop_id,
				}).then(res => {
					uni.hideLoading()
					httpRequest.toast(res.msg)
					if (res.code == 1) {
						this.getCateList()
					}
				}).catch(err => {
					uni.hideLoading()
				});
			},
			async excelfl() { //範例
				let res = await this.http.request('/api/index/getConfigInfoItem', 'POST', {
					pidtype: "otherset",
					type: "importmb"
				})
				window.open(res.data)
			},
			copyCate() { //整页复制
				this.copyIdList = []
				this.list.data.forEach(item => {
					this.copyIdList.push(item.id)
				})
				console.log(this.copyIdList)
				this.http.toast("複製成功")
			},
			async copyPaste() { //整页贴上
				let res = await this.http.request('/api/shop/copyClass', 'POST', {
					shop_id: this.shop_id,
					copy_id: this.copyIdList.join(), //复制ID
					id: this.topList[this.topList.length - 1].id, //目标id
				})
				if (res.code == 1) {
					this.http.toast("複製成功")
					this.getCateList()
				} else if (res.code == 0) {
					this.http.toast(res.msg)
				} else {
					this.http.toast('系統處理中，請稍後再試');
				}
			},
			backPage() {
				// console.log(this.topList.slice(1));
				uni.$emit("selectCate", this.topList.slice(1))
				uni.navigateBack(1)
			},
		},
	}
</script>

<style scoped>
	.smalltext {
		font-size: 24rpx;
	}

	.baibtn {
		padding: 15rpx 15rpx;
	}

	.itemlefttab {
		padding: 20rpx 0;
		width: 33.33%;
		text-align: center;
		border-right: none;
		border-radius: 10rpx 0 0 10rpx;
	}

	.itemcentertab {
		padding: 20rpx 0;
		width: 33.33%;
		text-align: center;
	}

	.itemrighttab {
		padding: 20rpx 0;
		width: 33.33%;
		text-align: center;
		border-left: none;
		border-radius: 0 10rpx 10rpx 0;
	}

	.borderhui {
		border: 1rpx solid rgba(50, 60, 160, .1);
	}

	.tiebianarrow {
		height: 50rpx;
		background-color: #ffb800;
		width: 30rpx;
		position: absolute;
		right: -15rpx;
		top: 50%;
		transform: translate(50%, -50%);
	}
</style>